package com.itheima.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.itheima.bean.User;
import com.itheima.service.impl.UserServiceImpl;
import com.itheima.utils.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/userServlet")
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //请求体乱码
        req.setCharacterEncoding("utf-8");
        //响应体乱码
        resp.setContentType("text/html;charset=utf-8");
        /*BufferedReader reader = req.getReader();
        String json = reader.readLine();
        ObjectMapper mapper = new ObjectMapper();
        //loginUser中只有前台页面传递过来的用户名密码
        User loginUser = mapper.readValue(json, User.class);*/

        //loginUser中只有前台页面传递过来的用户名密码

        User loginUser = JsonUtil.req2Bean(req, User.class);
        //调用service层去访问dao
        UserServiceImpl userService = new UserServiceImpl();

        //user中包含当前用户记录的所有信息
        User user=userService.login(loginUser);
        System.out.println(user);
        if (user !=null){
            //登陆成功1.将user存入session域对象中2.告诉前台登陆成功
            req.getSession().setAttribute("user",user);
            resp.getWriter().write("true");
        }else {
            resp.getWriter().write("false");
        }
    }
}
